package com.lap.auth.application.role;

import com.lap.auth.application.role.assembler.RoleAssembler;
import com.lap.auth.application.role.command.CreateDataScopeCmd;
import com.lap.auth.application.role.dto.RoleDataScopeDto;
import com.lap.auth.domain.role.repository.RoleDataScopeRepository;
import com.lap.auth.domain.role.service.RoleValidator;
import com.lap.auth.domain.role.valueobject.RoleDataScope;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@RequiredArgsConstructor
@Service
public class RoleDataScopeAppService {

  private final RoleAssembler roleAssembler;
  private final RoleValidator roleValidator;
  private final RoleDataScopeRepository roleDataScopeRepository;

  public void saveDataScope(Integer roleId, CreateDataScopeCmd cmd) {
    RoleDataScope roleDataScope = roleAssembler.toDomain(roleId, cmd);

    roleValidator.assertRoleExists(roleDataScope.roleId());
    roleDataScopeRepository.deleteByRoleId(roleDataScope.roleId());
    roleDataScopeRepository.save(roleDataScope);
  }

  public RoleDataScopeDto getRoleDataScopes(Integer roleId) {
    Optional<RoleDataScope> optional = roleDataScopeRepository.findByRoleId(roleId);
    return optional.map(roleAssembler::toDto).orElse(null);
  }
}
